<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ViewPage
 *
 * @author b4by
 */
class ViewPage extends MY_Controller
{

	function __construct() {
		parent::__construct();
		$this->load->model('model_page');
		$this->load->model('model_page_user');
	}

	public function index($id) {
		$page = $this->model_page->get_info($id);
//		pr($page);die;
		if(!$page)
			show_error(lang('page_not_found'));

		$this->load->model('model_page_catalogue');
		$cat_ids = $this->model_page_catalogue->get_list(array(
			'where' => array('page_id' => $page->id),
			'order' => array('cat_id', 'RANDOM')
		));
		$this->data['catalogue'] = $this->model_catalogue->get_info($cat_ids[0]->cat_id);

		$this->data['site_title'] = $page->title . ' | ' . $this->siteConfig->site_title;
		$this->data['page'] = $page;
		$this->data['temp'] = 'page/index';
		$this->data['others'] = $this->others($id);
		$page->registed = $this->model_page_user->get_total(array(
			'user_id'	=> $this->user->id,
			'page_id'	=> $id,
		));
		$this->load_view();
	}

	public function others($id) {
		$pages = $this->model_page->get_list(array(
			'where' => array(
//				'cat_id'	=> $cat_id,
				'p.id <>' => $id,
				'time >' => now() - 60 * 60 * 24 * 30
			),
			'limit' => array(0, 10),
			'order' => array('id', 'RANDOM')
		));
		return $pages;
	}

	public function register()
	{
		$this->load->helper('form');
		$this->load->library('form_validation');
		if($this->ajax){
			$this->form_validation->set_rules('page_id','lang:Packet','required||callback__check_page');
			if($this->form_is_valid()){
				$data = request_filter(array('page_id','comment'));
				$data['user_id'] = $this->user->id;
				$this->model_page_user->create($data);
				
				echo json_encode(array(
					'state'	=> 'success',
					'title'	=> lang('Caution'),
					'message'	=> lang('Registration success!'),
				));
			}
			else{
				echo json_encode(array(
					'state'	=> 'error',
					'errors'	=> $this->data['errors'],
					'message'	=> form_error_message($this->data['errors'])
				));
			}
		}
	}
	
	public function _check_page($id)
	{
		$info = $this->model_page->get_info($id);
		if(!$info){
			$this->form_validation->set_message(__FUNCTION__,lang('Invalid package!'));
			return FALSE;
		}
		
		$count = $this->model_page_user->get_total(array(
			'page_id'	=> $id,
			'user_id'	=> $this->user->id,
		));
		if($count>0){
			$this->form_validation->set_message(__FUNCTION__,lang('You have already registered this package!'));
			return FALSE;
		}
		return TRUE;
	}
}

?>
